package com.bstek.demo.urule;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.*;

import java.io.IOException;
import java.util.Map;

public class JsonUtils {

	public static String toJSON(Object object) throws IOException {
		ObjectWriter objectWriter = getObjectMapper().writerWithDefaultPrettyPrinter();
		return objectWriter.writeValueAsString(object);
	}

	public static <T> T fromJSON(String data, Class<T> clazz) throws Exception {
		return getObjectMapper().readValue(data, clazz);
	}

	public static Map<String, Object> fromJSONToMap(String data) throws Exception {
		return getObjectMapper().readValue(data, new TypeReference<Map<String, Object>>(){});
	}

	public static ObjectMapper getObjectMapper() {
		ObjectMapper mapper = new ObjectMapper();
		// 禁用未知属性的失败处理
		mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		// 设置返回null转为 空字符串""
		mapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
			@Override
			public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
				gen.writeString("");
			}
		});
		//mapper.disable(SerializationFeature.INDENT_OUTPUT);

		return mapper;
	}

}
